package com.hm.ibsm.auto;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.StringUtil;
import com.hm.ibsm.auto.helper.UserSession;
import com.hm.ibsm.manage.vo.auth.AuthUserVo;
import com.hm.ibsm.util.BeanUtil;
import com.hm.ibsm.util.R;

/**
 * @author shishun.wang
 * @date 2017年3月7日 下午6:19:35
 * @version 1.0
 * @describe
 */
public class SystemSessionHolder {

	// private static ThreadLocal<UserSession> LOCAL_SESSION = new
	// ThreadLocal<UserSession>();

	// public static void setUserSession(UserSession session) {
	// LOCAL_SESSION.set(session);
	// }

	public static UserSession getUserSession() {
		// return LOCAL_SESSION.get();
		Object obj = session().getAttribute(R.CURRENT_USER_LOGIN_SESSION);
		if (CommonUtil.isEmpty(obj)) {
			throw ServiceException.warning(ErrorCode.SESSION_OUT_TIME);
		}
		AuthUserVo userVo = (AuthUserVo) obj;
		UserSession session = new UserSession();
		BeanUtil.copyProperties(userVo, session);
		return session;
	}

	public static int currenPageNo() {
		String currenPageNo = request().getParameter("page");
		if (StringUtil.isBlankOrNull(currenPageNo)) {
			throw ServiceException.warning(ErrorCode.SESSION_OUT_TIME);
		}
		return Integer.parseInt(currenPageNo);
	}

	public static int currenPageSize() {
		String currenPageNo = request().getParameter("limit");
		if (StringUtil.isBlankOrNull(currenPageNo)) {
			throw ServiceException.warning(ErrorCode.SESSION_OUT_TIME);
		}
		return Integer.parseInt(currenPageNo);
	}

	private static HttpSession session() {
		return request().getSession();
	}

	private static HttpServletRequest request() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

	}
}
